$(document).ready(function() {
    initMenu();
    changeMenu();
});

function switchMenu(element) {
    let item = element.parentNode;
    let url = $(item).find(".menu-url")[0].innerText;
    if ([...item.classList].includes("active")) {
        $(item).removeClass("active")
    } else {
        $(item).addClass("active")
    }
    if ($(item).find(".sub-menu-title").length === 0) {
        window.location.href = url;
    }
    changeMenu();
}

function switchSubMenu(element) {
    let url = $(element).find(".menu-url")[0].innerText;
    if ([...element.classList].includes("active")) {
        $(element).removeClass("active")
    } else {
        $(element).addClass("active")
    }
    window.location.href = url;
    changeMenu();
}

function changeMenu() {
    let limitHeight = $(window).height() - 200;
    let menuHeight = 0;
    let cardcount = 0;
    $('.menu-item').each(function(i, n) {
        cardcount++;
        let childrenCount = $(n).find(".sub-menu-item").length;
        if ([...$(n)[0].classList].includes("active")) {
            cardcount += childrenCount
        }
        if (childrenCount > 0 && ![...$(n)[0].classList].includes("hasChildren")) {
            $(n).addClass("hasChildren")
        }
    });
    //菜单合计高度
    menuHeight = cardcount * 61 - 3;

    //菜单小于界限高度
    if (menuHeight < limitHeight) {
        $(".menu-empty").css("height", (limitHeight - menuHeight - 3 + "px"))
            // $(".right").css("height","calc(100vh - 200px)")
            // $(".menu").css("height","calc(100vh - 200px)")
    } else {
        $(".menu-empty").css("height", "0px")
            // $(".right").css("height", menuHeight + 'px')
            // $(".menu").css("height", menuHeight + "px")
    }
}

function initMenu() {
    let title = $("#currentTitle").text();
    $('.menu-item').each(function(i, n) {
        let itemTitle = $(n).find(".menu-title-text")[0].innerText;
        //无二级的
        if (itemTitle === title) {
            $(n).addClass("active");
            return false
        } else {
            //有二级的查询子节点
            let subarr = $(n).find(".sub-menu-title");
            for (let i = 0; i < subarr.length; i++) {
                if (subarr[i].innerText === title) {
                    $(subarr[i]).addClass("active");
                    $(n).addClass("active");
                    break;
                    return false;
                }
            }
        }
    });
}